package com.health.work.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.health.work.R;
import com.health.work.model.AddressBean;
import com.health.work.model.Doctorbean;
import com.health.work.parse.AddressParse;
import com.health.work.parse.TypeParse;
import com.health.work.utils.DefaultJSONData;
import com.health.work.utils.HEALTHPASSPORT;
import com.health.work.utils.RequestParamtersUtil;
import com.health.work.utils.TipsUtil;
import com.health.work.utils.UploadUtil;
import com.health.work.utils.UserInfoUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


/**
*
* 项目名称：HealthNet
* 类名称：医师  录入信息
* 类描述：
* 创建人：Zhai
* 创建时间：2012-11-8 下午2:26:42
* 修改人：Zhai
* 修改时间：2012-11-8 下午2:26:42
* 修改备注：
* @version
*
*/
public class RegisteDocInfoInputActivity extends Activity implements OnClickListener {
	
	/* 拍照的照片存储位置 */
	private static final File PHOTO_DIR = new File(
			Environment.getExternalStorageDirectory() + "/DCIM/Camera");

	/* 用来标识请求照相功能的activity */
	private static final int CAMERA_WITH_DATA = 3023;

	/* 用来标识请求gallery的activity */
	private static final int PHOTO_PICKED_WITH_DATA = 3021;

	protected static final int SUCCESS = 0;

	protected static final int ERROR = 1;

	private File mCurrentPhotoFile;// 照相机拍照得到的图片
	
	private ProgressDialog dialog;
	private Button btnBack;
	private Button btnSave;
	private TextView back;
	
	private Spinner spinner1;
	private Spinner spinner2;
	private Spinner spinner3;
	private Spinner spinner4;
	private List<String> spinnerList1;
	private List<String> spinnerList2;
	private List<String> spinnerList3;
	private List<String> spinnerList4;
	private ArrayList<AddressBean> provinceList;
	private ArrayList<AddressBean> cityList;
	private ArrayList<AddressBean> areaList;
	private ArrayList<AddressBean> roadList;
	protected String province;
	protected String city;
	protected String area;
	protected String road="";
	protected AddressParse parse;
	
	protected TypeParse typeParse;
	private List<String> list_sex;
	private Spinner spinner_doc;
	private Spinner spinner_major;
	private Spinner spinner_sex;
	protected String idCertificateType;
	protected String idProfessionalCategory;
	protected String sex;

	private Thread thread;
	private String passport_img="";
	private String product_img="";

	private int type_action;
	private EditText real_name;
	
	private TextView user_pic;
	private TextView puc_pic;
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SUCCESS:
				TipsUtil.showAlertFinish(RegisteDocInfoInputActivity.this, null,
						"恭喜您，上传信息成功！");
				break;
			case ERROR:
				TipsUtil.showAlert(RegisteDocInfoInputActivity.this, null,
						"上传信息失败！");
				break;
			default:
				break;
			}

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.registerdocinputinfo);
		init();
	}

	private void init() {
		btnBack=(Button)this.findViewById(R.id.btnBack);
		btnSave=(Button)this.findViewById(R.id.btnSave);
		back=(TextView)this.findViewById(R.id.pic_user);
//		user_pic=(TextView)this.findViewById(R.id.pic_doc);
		puc_pic=(TextView)this.findViewById(R.id.back);
		real_name=(EditText)this.findViewById(R.id.real_name);
		
	    btnBack.setOnClickListener(this);
		btnSave.setOnClickListener(this);
		back.setOnClickListener(this);
//		user_pic.setOnClickListener(this);
		puc_pic.setOnClickListener(this);
		
		request("0", 1);
		}
	
	private void spinnerother(){//其它的类别
		if(typeParse==null){
			return;
		}
		spinner_doc=(Spinner)this.findViewById(R.id.spinner_doc_kink);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, typeParse.nameListCertificateType); 
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner_doc.setAdapter(adapter);
	    spinner_doc.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ 
            public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) { 
            	idCertificateType=typeParse.typeListCertificateType.get(pos).TypeId;
            } 
            public void onNothingSelected(AdapterView<?> arg0) { 
            	idCertificateType=typeParse.typeListCertificateType.get(0).TypeId;
            } 
        }); 
	    
	    spinner_major=(Spinner)this.findViewById(R.id.spinner_major_kink);
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, typeParse.nameListProfessionalCategory); 
	    adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner_major.setAdapter(adapter2);
	    spinner_major.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ 
            public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) { 
            	idProfessionalCategory=typeParse.typeListProfessionalCategory.get(pos).TypeId;
            } 
            public void onNothingSelected(AdapterView<?> arg0) { 
            	idProfessionalCategory=typeParse.typeListProfessionalCategory.get(0).TypeId;
            } 
        }); 
	    
	    list_sex=new ArrayList<String>();
	    list_sex.add("男");
		list_sex.add("女");
		
		spinner_sex=(Spinner)this.findViewById(R.id.spinner_sex);
		ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, list_sex); 
	    adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner_sex.setAdapter(adapter3);
	    spinner_sex.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ 
            public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) { 
            	sex=list_sex.get(pos);
            } 
            public void onNothingSelected(AdapterView<?> arg0) { 
            	sex=list_sex.get(0);
            } 
        }); 
	}
	
	private void spinnerRelation1(){//省
		if(spinnerList1==null){
			return;
		}
		spinner1=(Spinner)this.findViewById(R.id.spinner1);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, spinnerList1); 
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner1.setAdapter(adapter);
		spinner1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ 
            public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) { 
            	request(provinceList.get(pos).provinceId,2);
            	province=provinceList.get(pos).provinceId;
            } 
            public void onNothingSelected(AdapterView<?> arg0) { 
            	province=provinceList.get(0).provinceId;
            } 
        }); 
	}
	private void spinnerRelation2(){//市
		if(spinnerList2==null){
			return;
		}
		spinner2=(Spinner)this.findViewById(R.id.spinner2);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, spinnerList2); 
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner2.setAdapter(adapter);
		spinner2.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ 
            public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) { 
            	request(cityList.get(pos).provinceId,3);
            	city=cityList.get(pos).provinceId;
            } 
            public void onNothingSelected(AdapterView<?> arg0) { 
            	city=cityList.get(0).provinceId;
            } 
        }); 
	}
	private void spinnerRelation3(){//区
		if(spinnerList3==null){
			return;
		}
		spinner3=(Spinner)this.findViewById(R.id.spinner3);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, spinnerList3); 
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner3.setAdapter(adapter);
		spinner3.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ 
            public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) { 
            	request(areaList.get(pos).provinceId,4);
            	area=areaList.get(pos).provinceId;
            } 
            public void onNothingSelected(AdapterView<?> arg0) { 
            	area=areaList.get(0).provinceId;
            } 
        }); 
	}

	private void spinnerRelation4(){//其它
		if(spinnerList4==null){
			return;
		}
		spinner4=(Spinner)this.findViewById(R.id.spinner4);
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, spinnerList4); 
	    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	    spinner4.setAdapter(adapter);
		spinner4.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ 
            public void onItemSelected(AdapterView<?> arg0, View arg1, int pos, long arg3) { 
            	road=roadList.get(pos).provinceId;
            } 
            public void onNothingSelected(AdapterView<?> arg0) {
            	road=roadList.get(0).provinceId;
            } 
        }); 
	}
	
	protected void request(final String provinceId,final int i) {
		final Context context = this;
		AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {

			@Override
			protected void onPreExecute() {
				if(dialog!=null){
					
				}else{
					dialog = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
					dialog.setCancelable(true);
				}
				if(typeParse==null){
					typeParse=new TypeParse();
				}
				
				parse=new AddressParse();
			}
			@Override
			protected Void doInBackground(Void... params) {
				new RequestParamtersUtil().GetByUpId(provinceId, parse);
				if(typeParse.typeListCertificateType!=null){
					
				}else{
					new RequestParamtersUtil().GetType(typeParse);
				}
				return null;
			}			
			@Override
			protected void onPostExecute(Void result) {
				
				if(spinner_doc==null){
					spinnerother();
				}
				
				if(i==1){
					provinceList=parse.addressList;
					spinnerList1=parse.nameList;
					spinnerRelation1();
				}else if(i==2){
					cityList=parse.addressList;
					spinnerList2=parse.nameList;
					spinnerRelation2();
				}else if(i==3){
					areaList=parse.addressList;
					spinnerList3=parse.nameList;
					spinnerRelation3();
				}else if(i==4){
					roadList=parse.addressList;
					spinnerList4=parse.nameList;
					spinnerRelation4();
					dialog.dismiss();
					dialog=null;
				}
			}
		};
		asyncLoad.execute(null);
	}

	
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.back:
			finish();
			break;
		case R.id.btnSave:
			submit();
			break;
		case R.id.btnBack:
			finish();
			break;
		case R.id.pic_doc:
			type_action=2;
			doPickPhotoAction();
			break;
		case R.id.pic_user:
			type_action=1;
			doPickPhotoAction();
			break;
		default:
			break;
		}
	}
	
	//上传商家信息的函数，暂时设计上是没有这个按钮的
		private void submit() {
			final Doctorbean bus=new Doctorbean();
			bus.MobilePhone=UserInfoUtils.getUserProperty(this, HEALTHPASSPORT.MOBILEPHONE);
			bus.Province=province;
			bus.City=city;
			bus.CountyArea=area;
			bus.Township=road;
			bus.CertificateTypeId=idCertificateType;
			bus.ProfessionalCategoryId=idProfessionalCategory;
			bus.Sex=sex;
			if(!TipsUtil.isNull(real_name)){
				
			}else{
				TipsUtil.showAlert(this, null, "真实姓名输入不正确！");
				return;
			}
			bus.Name=real_name.getText().toString();
			if(type_action==1){
				bus.photo=passport_img;
			}else{
				bus.photo=product_img;
			}
			if(thread==null){
				thread =new Thread(new Runnable() {
					@Override
					public void run() {
						new RequestParamtersUtil().Save(bus, new DefaultJSONData() {
		
									@Override
									public void parse(JSONObject object)
											throws JSONException {
									}
		
									@Override
									public void parse(JSONArray array)
											throws JSONException {
									}
		
									@Override
									public void parse(String result)
											throws JSONException {
										Log.e("SaveBusiness", result);
										if("1".equals(result)){
											handler.sendEmptyMessage(ERROR);
										}else if("0".equals(result)){
											handler.sendEmptyMessage(SUCCESS);
										}
									}
								});
						
					}
				});
			}
			thread.start();
		}

		/**
		 * 
		 * 88888888888888888888888888888888888888888888888888888888888888888888888888
		 */

		// 以下代码是调用摄像头或者系统相册

		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			super.onActivityResult(requestCode, resultCode, data);
			if (resultCode != Activity.RESULT_OK)
				return;
			switch (requestCode) {
				case PHOTO_PICKED_WITH_DATA: {// 调用Gallery返回的
					final Bitmap photo = data.getParcelableExtra("data");
					System.out.println(photo);
//					String imageStr = BitmapBase64.getBitmapStringBase64(photo);
					upFile(1,null,photo);
					break;
				}
				case CAMERA_WITH_DATA: {// 照相机程序返回的,再次调用图片剪辑程序去修剪图片
				// doCropPhoto(mCurrentPhotoFile);
					upFile(2,mCurrentPhotoFile,null);
					break;
				}
			}
		}

		public void doPickPhotoAction() {
			final Context dialogContext = new ContextThemeWrapper(this,
					android.R.style.Theme_Light);
			String cancel = "返回";
			String[] choices;
			choices = new String[2];
			choices[0] = "拍照"; // 拍照
			choices[1] = "从相册中选择"; // 从相册中选择
			final ListAdapter adapter = new ArrayAdapter<String>(dialogContext,
					android.R.layout.simple_list_item_1, choices);

			final AlertDialog.Builder builder = new AlertDialog.Builder(
					dialogContext);
			builder.setTitle("选择方式");
			builder.setSingleChoiceItems(adapter, -1,
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							switch (which) {
							case 0: {
								String status = Environment
										.getExternalStorageState();
								if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
									doTakePhoto();// 用户点击了从照相机获取
								} else {
									Toast.makeText(
											RegisteDocInfoInputActivity.this,
											"出现异常", Toast.LENGTH_LONG).show();
								}
								break;

							}
							case 1:
								doPickPhotoFromGallery();// 从相册中去获取
								break;
							}
						}
					});
			builder.setNegativeButton(cancel,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}

					});
			builder.create().show();
		}

		/**
		 * 拍照获取图片
		 * 
		 */
		protected void doTakePhoto() {
			try {
				mCurrentPhotoFile = new File(PHOTO_DIR, "health.jpg");// 给新照的照片文件命名
				final Intent intent = getTakePickIntent(mCurrentPhotoFile);
				startActivityForResult(intent, CAMERA_WITH_DATA);
			} catch (ActivityNotFoundException e) {
				Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
			}
		}

		public static Intent getTakePickIntent(File f) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE, null);
			intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
			return intent;
		}

		// 请求Gallery程序
		protected void doPickPhotoFromGallery() {
			try {
				// Launch picker to choose photo for selected contact
				final Intent intent = getPhotoPickIntent();
				startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			} catch (ActivityNotFoundException e) {
				Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
			}
		}

		// 封装请求Gallery的intent
		public static Intent getPhotoPickIntent() {
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
			intent.setType("image/*");
			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 80);
			intent.putExtra("outputY", 80);
			intent.putExtra("return-data", true);
			return intent;
		}

		protected void doCropPhoto(File f) {
			try {
				// 启动gallery去剪辑这个照片
				final Intent intent = getCropImageIntent(Uri.fromFile(f));
				startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			} catch (Exception e) {
				Toast.makeText(this, "ERROR!!", Toast.LENGTH_LONG).show();
			}
		}

		/**
		 *  调用图片剪辑程序
		 */
		public static Intent getCropImageIntent(Uri photoUri) {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(photoUri, "image/*");
			intent.putExtra("crop", "true");
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("outputX", 80);
			intent.putExtra("outputY", 80);
			intent.putExtra("return-data", true);
			return intent;
		}
		
		protected void upFile(final int kind,final File file,final Bitmap bitmap) {
			final Context context = this;
			AsyncTask<Void, Void, Void> asyncLoad = new AsyncTask<Void, Void, Void>() {
				 private ProgressDialog dialog2 = null;
				 private String url="";
				@Override
				protected void onPreExecute() {
					if (dialog2 != null) {
					} else {
						dialog2 = ProgressDialog.show(context, "", "正在加载数据，请稍候...");
						dialog2.setCancelable(true);
					}
				}

				@Override
				protected Void doInBackground(Void... params) {
					if(kind==2){
						url=UploadUtil.uploadFile(file, HEALTHPASSPORT.URL_PIC,
							"file");
					}else{
						url=UploadUtil.uploadFile(bitmap,
								HEALTHPASSPORT.URL_PIC, "file");	
					}
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
						dialog2.dismiss();
						dialog2 = null;
						if(type_action==1){
							passport_img=url;
						}else if(type_action==2){
							product_img=url;
						}
				}
			};
			asyncLoad.execute(null);
		}


}
